package com.example.test04

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import cn.edu.sicnu.cardgame.CardMatchingGame

class GameActivity : AppCompatActivity(), View.OnClickListener {

    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_game)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
        for(v in gridLayout.children){
            v.setOnClickListener(this)
            cardButtons.add(v as Button)
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()
        findViewById<Button>(R.id.reset).setOnClickListener({
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        })
    }

    override fun onClick(v: View?) {
        val index = cardButtons.indexOf(v)
        game.chooseCardAtIndex(index)
        updateUI()
    }

    fun updateUI(){
        for(btn in cardButtons){
            val index = cardButtons.indexOf(btn)
            val card = game.cardAtIndex(index)
            btn.isEnabled = !card.isMatched
            if(card.isChosen){
                btn.text = card.toString()
                btn.setBackgroundColor(Color.WHITE)
            }else{
                btn.text = ""
                btn.setBackgroundResource(R.mipmap.card)
            }
        }
        findViewById<TextView>(R.id.score).text = String.format("%s%d", "Score: ",game.score)
    }
}